# -*- coding: utf-8 -*-
import paramiko
import os
import datetime
import ConfigParser
config = ConfigParser.RawConfigParser()

ROOT=os.path.dirname(os.path.realpath(__file__))

config.read(os.path.join(ROOT,"../config/server.ini"))

print ROOT,"../config/server.ini"


a=datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
#生成包名
a=datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')

try:
    name = raw_input("请输入要重启的服务器代号(具体的参见config目录下的server.ini:")


    print name
    ip=config.get(name,'ip')
    port=config.getint(name,'port')
    username=config.get(name,'user')
    password=config.get(name,'password')

    d=config.get(name,'framework')
    gamename = config.get(name,'gamename')


    s="""
        chmod 777 build%sinstaller.sh
        sh build%sinstaller.sh %s %s
    """%(d,d,a,gamename)
    filename = "skynetbin_"+a+".tar.gz"
    print s

    os.system(s)
    print '准备开始连接服务器:' + ip,port,username,password
    print 'IP:' + ip
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,username,password)

    tran = paramiko.Transport((ip,port))
    tran.connect(username=username,password=password)
    print "连接成功"
    s="""
        cd ~
        mkdir proj
    """
    stdin,stdout,stderr = ssh.exec_command(s)

    sftp=paramiko.SFTPClient.from_transport(tran)

    print "上传文件",filename
    sftp.put("./out/"+filename,"/data/%s"%(filename))
    sftp=paramiko.SFTPClient.from_transport(tran)

    tran.close()

    print "解压缩文件"
    s="""
        cd ~
        cd /data
        tar -zxf %s
        cd /data/%sbin/%s
        `pwd`

    """%(filename,d,name)
    stdin,stdout,stderr = ssh.exec_command(s)

    print "编译skynet"

    ssh.close()
except Exception as e:
    print e
    # raise
else:
    pass
finally:
    pass
